package cn.org.xuanguang.kepler.hormos.rdb.dml.warrper;

import cn.org.xuanguang.kepler.hormos.rdb.entity.IEntity;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.Optional;
import java.util.function.Supplier;

import static cn.org.xuanguang.kepler.hormos.rdb.jpa.mapper.MetaTableToDslUtils.columnWrapper;

/**
 * @param <T>
 */
public class SingleObjectMapper<T extends Serializable> implements ResultWrapper<T, Object> {
    /**
     * 需要转换的类对象
     */
    private final Supplier<T> entityInstanceSupplier;


    /**
     * 结果对象，通常是javabean
     */
    T result;

    public SingleObjectMapper(Supplier<T> supplier) {
        this.entityInstanceSupplier = supplier;
    }


    @Override
    public T newRowInstance() {
        Class<? extends IEntity> entity = (Class<? extends IEntity>) entityInstanceSupplier.get();
        return (T) BeanUtils.instantiateClass(entity);
    }

    @Override
    public void wrapColumn(ColumnWrapperContext<T> context) {
        result = context.getRowInstance();
        Class<T> entity = (Class<T>) entityInstanceSupplier.get();
        // 此处会根据jpa映射包装
        columnWrapper(result, entity, context);
    }

    @Override
    public boolean completedWrapRow(T result) {
        this.result = result;
        return false;
    }

    @Override
    public Object getResult() {
        return Optional.ofNullable(result).orElse(newRowInstance());
    }
}
